<template>
  <el-container>
    <el-aside width="350px">
      <el-tabs type="border-card">
        <el-tab-pane label="输入要素">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="srcRun">运行</el-button>
            <el-button size="mini" type="text" @click="remove('geojson_point')">移除</el-button>
          </div>
          <el-form :model="srcParameter" :rules="srcRules" ref="srcParameter">
            <el-form-item prop="srcTable" label="要素数据">
              <el-input  v-model="srcParameter.srcTable" autocomplete="off" placeholder="要素数据"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane> 
        <el-tab-pane label="邻近要素">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="nearRun">运行</el-button>
            <el-button size="mini" type="text" @click="remove('center')">移除</el-button>
          </div>
          <el-form :model="nearParameter" :rules="nearRules" ref="nearParameter">
            <el-form-item prop="newTable" label="要素数据">
              <el-input  v-model="nearParameter.nearTable" autocomplete="off" placeholder="要素数据"></el-input>
            </el-form-item>           
          </el-form>
        </el-tab-pane>  
        <el-tab-pane label="开始分析">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="newRun">运行</el-button>
            <el-button size="mini" type="text" @click="remove('near_point')">移除</el-button>
          </div>
          <el-form :model="newParameter" :rules="rules" ref="newParameter">
            <el-form-item prop="srcTable" label="目标数据">
              <el-input  v-model="newParameter.srcTable" autocomplete="off" placeholder="目标数据"></el-input>
            </el-form-item>
            <el-form-item prop="nearTable" label="邻近要素">
              <el-input  v-model="newParameter.nearTable" autocomplete="off" placeholder="邻近要素"></el-input>
            </el-form-item>
            <el-form-item prop="radius" label="半径">
              <el-input  v-model="newParameter.radius" autocomplete="off" placeholder="半径"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>    
      </el-tabs>
    </el-aside>
    <el-main>
      <div class="mapbox-maps">
        <div id="map">      
        </div> 
      </div>   
    </el-main>
  </el-container>  
</template>
<script>
export default{
    name:'PostgisNearAnalysis',
    data(){
      return{
        oldGeosjon:'',
        geojsonPath: 'https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json',
        drawer: false,
        map:{},
        geojson: {        
          type:'geojson',
          data:{
          "type": "FeatureCollection",
          "features":[]
          }
        },
        jsonData: {},
        srcParameter:{
          srcTable:"hainan_weather",//原始数据
        },
        nearParameter:{
          nearTable:"hainan_weather_grid_point"
        },
        newParameter:{
          srcTable:"hainan_weather",
          nearTable:"hainan_weather_grid_point",
          radius:"1000"
        },
        srcRules: {
          srcTable: [
            { required: true, message: '请输入原始数据', trigger: 'blur' },
          ],                
        },
        nearRules:{
           nearTable: [
            { required: true, message: '请输入邻近数据', trigger: 'blur' },
          ],  
        },
        rules:{
          srcTable: [
            { required: true, message: '请输入原始数据', trigger: 'blur' },
          ],
          nearTable: [
            { required: true, message: '请输入邻近数据', trigger: 'blur' },
          ],
          radius: [
            { required: true, message: '请输入半径', trigger: 'blur' },
          ]
        },
      }
    },
    mounted() {
      this.loadMap()
    },
    beforeDestroy(){
      this.map.remove()

    },
    methods:{
        
      loadMap() {
        // 英文标注转换为中文   
        // mapboxgl.setRTLTextPlugin(
        //   "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js"
        // );
        this.map =  new mapboxgl.Map({
            accessToken: 'pk.eyJ1Ijoienh0d24iLCJhIjoiY2wzanV3bHduMTZwejNrcXcyd3B1bzBieiJ9.aW_TDqLomftwPvBu7OWqwQ',
            container: 'map',
            style: 'mapbox://styles/mapbox/outdoors-v10', // stylesheet location
            center: [110.47 ,  19.23],  //[116.79507,32.65542], // starting position [lng, lat]
            zoom: 8, // starting zoom
            hash: false,
            //pitch: 45,  //地图的角度，不写默认是0，取值是0-60度，一般在3D中使用
            bearing: 0, //地图的初始方向，值是北的逆时针度数，默认是0，即是正北
            antialias: true, //抗锯齿，通过false关闭提升性能
        })
        // 设置语言
        // var language = new MapboxLanguage({ defaultLanguage: "zh" });
        // this.map.addControl(language);

        //地图导航
        var nav = new mapboxgl.NavigationControl();
        this.map.addControl(nav, 'top-right');

        // 比例尺
        var scale = new mapboxgl.ScaleControl({
            maxWidth: 100,
            unit: "metric"
        });
        this.map.addControl(scale,"bottom-left");

        // 全图
        this.map.addControl(new mapboxgl.FullscreenControl());
        // 定位
        this.map.addControl(
            new mapboxgl.GeolocateControl({
            positionOptions: {
                enableHighAccuracy: true
            },
            trackUserLocation: true
            })
        );
        let that = this;
        this.map.on('load',function () {
          console.log(that)
          that.map.addSource("geojson_point",that.geojson);
          that.map.addSource("center",that.geojson);
          that.map.addSource("near_point",that.geojson);
          that.map.addLayer({
              id: "geojson_point",
              type: "circle",
              source: "geojson_point",
              paint: {
                  "circle-radius": 5,
                  "circle-color": "#00A54E",
              }
          }); 
          that.map.addLayer({
              id: "near_point",
              type: "circle",
              source: "near_point",
              paint: {
                  "circle-radius": 3,
                  "circle-color": "#A20055",
              }
          }); 
          that.map.addLayer({
              id: "center_point",
              type: "circle",
              source: "center",
              paint: {
                  "circle-radius": 3,
                  "circle-color": "#FF0000",
              }
          });
            
        })          
      },  
      /**
      * 渲染geojson  line数据
      * 
      */
      srcRun(){
        let that = this
        that.$refs["srcParameter"].validate((valid) => {       
          if (valid) {
            let that = this           
            let fd =  new URLSearchParams()
            fd.append("srcTable",that.srcParameter.srcTable)                     
            let url = "/analysis/geojson"
            that.$axios.post(url, fd)       
            .then(function (res) {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.geom)    
                features.push({
                "type": "Feature",
                "geometry":geom,
                "properties": {"status": "status"}
                })	
              
              })
              that.map.getSource('geojson_point').setData({
                  "type": "FeatureCollection",
                  "features":[]
              })
              that.map.getSource('geojson_point').setData({
                  "type": "FeatureCollection",
                  "features":features
              })
            })
            .catch(function (error) {       
              console.log(error);
            })             
          } else {
            console.log('error submit!!');
            return false;
          }
        });                
      },	
      /**
      * 渲染geojson  point数据
      * 
      */
      nearRun(){
        let that = this
        that.$refs["nearParameter"].validate((valid) => {       
          if (valid) {
            let that = this           
            let fd =  new URLSearchParams()
            fd.append("srcTable",that.nearParameter.nearTable)                               
            let url = "/analysis/geojson"
            that.$axios.post(url, fd)       
            .then(function (res) {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.geom)    
                features.push({
                "type": "Feature",
                "geometry":geom,
                "properties": {"status": "status"}
                })	
              
              })
              that.map.getSource('center').setData({
                  "type": "FeatureCollection",
                  "features":[]
              })
              that.map.getSource('center').setData({
                  "type": "FeatureCollection",
                  "features":features
              })
            })
            .catch(function (error) {       
              console.log(error);
            })             
          } else {
            console.log('error submit!!');
            return false;
          }
        });                
      },	
      /**
      * 渲染网格数据
      * 
      */
      newRun(){
        let that = this
        that.$refs["newParameter"].validate((valid) => {       
          if (valid) {
            let that = this           
            let fd =  new URLSearchParams()
            fd.append("srcTable",that.newParameter.srcTable)   
            fd.append("nearTable",that.newParameter.nearTable)
            fd.append("radius",that.newParameter.radius)                            
            let url = "/near/near_data"
            that.$axios.post(url, fd)       
            .then(function (res) {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.row_to_json.value)    
                features=geom.features              
              })
              that.map.getSource('near_point').setData({
                  "type": "FeatureCollection",
                  "features":[]
              })
              that.map.getSource('near_point').setData({
                  "type": "FeatureCollection",
                  "features":features
              })
            })
            .catch(function (error) {       
              console.log(error);
            })             
          } else {
            console.log('error submit!!');
            return false;
          }
        });                
      },	
      remove(sourceId){
        let that = this
        that.map.getSource(sourceId).setData({
            "type": "FeatureCollection",
            "features":[]
        })

      },
   
    }
}

</script>
<style scoped lang="scss">
 @import "../../../public/mapbox/mapbox-gl.css";
 .mapbox-maps {
    width: 100%;
    height: calc(100vh - 50px);
    position: relative;
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        bottom:0;
        right: 0;        
    }
    
}
.mapboxgl-canvas {
    outline: none;
}
  /* 隐藏mapbox商标 */
.mapboxgl-ctrl-logo {
    display: none;
} 
.el-aside {
    overflow: auto;
    box-sizing: border-box;
    flex-shrink: 0;
    width: 200px;
    // border: 1px solid red;
    line-height: 19px;
    padding: 10px;
    text-align: left;
}
.jv-container .jv-code.boxed {
    max-height: 100%;
}
</style>